import { Scene, Physics, GameObjects } from "phaser";
import { Player } from "./Player";
import { Bullet } from "./Bullet";
import { Enemy } from "./Enemy";
import { Boom } from "./Boom";

// 场景元素
let background: GameObjects.TileSprite;
let player: Player;
let enemys: Physics.Arcade.Group;
let bullets: Physics.Arcade.Group;
let booms: GameObjects.Group;
let scoreText: GameObjects.Text;

// 场景数据
let score: number;

export class Main extends Scene {
    constructor() {
        super("Main");
    }
    create() {
        let { width, height } = this.cameras.main;
        // 创建背景
        background = this.add.tileSprite(0, 0, width, height, "background").setOrigin(0, 0);

        // 创建玩家
        player = new Player(this);

        // 创建敌军
        enemys = this.physics.add.group({
            frameQuantity: 30,
            key: "enemy",
            enable: false,
            active: false,
            visible: false,
            classType: Enemy,
        });

        // 创建子弹
        bullets = this.physics.add.group({
            frameQuantity: 15,
            key: "bullet",
            enable: false,
            active: false,
            visible: false,
            classType: Bullet,
        });

        // 创建爆炸
        booms = this.add.group({
            frameQuantity: 30,
            key: "boom",
            active: false,
            visible: false,
            classType: Boom,
        });

        // 分数
        score = 0;
        scoreText = this.add.text(10, 10, "0", {
            fontFamily: "Arial",
            fontSize: 20,
        });

        // 注册事件
        this.addEvent();
    }
    // 注册事件
    addEvent() {
        
        this.time.addEvent({
            delay: 2000,
            callback: () => {
                for (let i = 0; i < 2; i++) {
                    enemys.getFirstDead()?.born(); // 假设 getFirstDead 和 born 方法已经定义
                }

            },
            callbackScope: this,
            repeat: -1
        });

        this.time.addEvent({
            delay: 300,
            callback: () => {
                // 检查是否有活着的敌军
                if (enemys.countActive(true) > 0) {
                    let target = this.getNearestEnemy();
                    if (target) {
                        let bullet = bullets.getFirstDead();
                        if (bullet) {
                            console.log('进来');
                            // 假设修改了fire方法以接受目标的x和y坐标
                            bullet.fire(player.x, player.y - 32, target.x, target.y);
                        }
                    }
                }
            },
            callbackScope: this,
            repeat: -1
        });
        

        // 子弹和敌军碰撞
        this.physics.add.overlap(bullets, enemys, this.hit, null, this);
        // 玩家和敌军碰撞
        this.physics.add.overlap(player, enemys, this.gameOver, null, this);
    }
    // 子弹击中敌军
    hit(bullet, enemy) {
        // 子弹和敌军隐藏
        enemy.disableBody(true, true);
        bullet.disableBody(true, true);
        // 显示爆炸
        booms.getFirstDead()?.show(enemy.x, enemy.y);
        // 分数增加
        scoreText.text = String(++score);
    }
    // 游戏结束
    gameOver() {
        // 暂停当前场景，并没有销毁
        this.sys.pause();
        // 保存分数
        this.registry.set("score", score);
        // 打开结束场景
        this.game.scene.start("End");
    }
    update() {
        // 设置背景瓦片不断移动
        background.tilePositionY -= 1;
    }


    // 添加一个方法来找到最近的敌人
    getNearestEnemy() {
        let closest = null;
        let closestDistance = Infinity;
        enemys.getChildren().forEach((enemy) => {
            if (enemy.active) {
                let distance = Phaser.Math.Distance.Between(player.x, player.y, enemy.x, enemy.y);
                if (distance < closestDistance) {
                    closest = enemy;
                    closestDistance = distance;
                }
            }
        });
        return closest;
    }
}
